package cn.otrue.patienthealthmanager.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.filetransfer.FileTransfer.Status;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.adapter.DoctorCharAdpater;
import cn.otrue.patienthealthmanager.bean.ChatModle;
import cn.otrue.patienthealthmanager.bean.DoctorBaseinfo;
import cn.otrue.patienthealthmanager.bean.HistoryChat;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.utils.MyRecorder;
import cn.otrue.patienthealthmanager.view.XListView;
import cn.otrue.patienthealthmanager.view.XListView.IXListViewListener;
import cn.otrue.patienthealthmanager.xmpp.XmppTool;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;

/**
 * 找医生->聊天
 * 
 * @author G
 * 
 */
public class DoctorChatActivity extends BaseActivity implements
		IXListViewListener {
	private List<ChatModle> data;
	private XListView lv_doctor_Chat;
	private String friendName;

	private EditText et_chat_log_msg;
	private TextView tv_chat_log_send;
	private SimpleDateFormat formatBuilder;

	private ImageView iv_catt_soundBtn;
	private Dialog dialog;
	private DoctorCharAdpater adapter;
	private ImageView voice_bt;

	private LinearLayout photo_ll;

	private LinearLayout voice_play_ll;
	private Button recordBt;
	private ImageView playBt;
	private ProgressBar bar;
	private Thread timeThread;
	private TextView dialog_tv;
	private ImageButton dialog_image;
	private int voiceTime;
	private MediaPlayer media;
	private static final int RESULT_LOAD_IMAGE = 1;
	private static final int TAKE_PICTURE = 0;
	public List<String> drr = new ArrayList<String>();
	private Uri photoUri;
	private static int MAX_TIME = 2 * 60; // 最长录制时间，单位秒，0为无时间限制
	private static int MIX_TIME = 1; // 最短录制时间，单位秒，0为无时间限制，建议设为1
	private static int RECORD_NO = 0; // 不在录音
	private static int RECORD_ING = 1; // 正在录音
	private static int RECODE_ED = 2; // 完成录音
	private static int RECODE_STATE = 0; // 录音的状态
	private static float recodeTime = 0.0f; // 录音的时间
	private static double voiceValue = 0.0; // 麦克风获取的音量值
	private static boolean playState = false; // 播放状态
	private FileTransferRequest request;
	private Thread barThread;
	private DbUtils db;
	// /////////////////////////////Handler////////////////////////////////////
	public Handler messageHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case 1:
				// 获取消息并显示
				try {
					String[] args = (String[]) msg.obj;

					ChatModle ChatModle = new ChatModle(args[0], "",
							MyConst.getACCOUNT(), "", args[1], "",
							MyConst.CHAT_IN, formatBuilder.parse(args[2]), 100);
					db.save(ChatModle);
					data.add(ChatModle);
					// 刷新适配器
					adapter.notifyDataSetChanged();
				} catch (DbException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};
	public Handler fileHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {

			case 1:

				break;

			case 2:
				try {
					Toast.makeText(DoctorChatActivity.this, "接收成功!",
							Toast.LENGTH_SHORT).show();

					ChatModle ChatModle = new ChatModle(MyConst.IN_USER, "",
							MyConst.getACCOUNT(), "", "", msg.obj.toString(),
							MyConst.CHAT_IN, new Date(), 100);

					db.save(ChatModle);
					data.add(ChatModle);
					adapter.notifyDataSetChanged();

				} catch (DbException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				break;
			case 3:
				ChatModle outChatModle;
				if (fileType == MyConst.FILE_AAC) {
					outChatModle = new ChatModle(friendName, "",
							MyConst.getACCOUNT(), "", "", voicePath,
							MyConst.CHAT_OUT, new Date(), 0);
				} else {
					outChatModle = new ChatModle(friendName, "",
							MyConst.getACCOUNT(), "", "", photoFile,
							MyConst.CHAT_OUT, new Date(), 0);
				}

				data.add(outChatModle);

				// 刷新适配器
				adapter.notifyDataSetChanged();
			case 4:
				// 发送中

				data.get(data.size() - 1).setSchedule(msg.arg1);

				// 刷新适配器
				adapter.notifyDataSetChanged();
				break;
			case 5:
				// 发送完毕
				try {
					Toast.makeText(DoctorChatActivity.this, "发送成功!",
							Toast.LENGTH_SHORT).show();

					data.get(data.size() - 1).setSchedule(100);

					db.save(data.get(data.size() - 1));

					// 刷新适配器
					adapter.notifyDataSetChanged();

				} catch (DbException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			case 6:
				Toast.makeText(DoctorChatActivity.this, "对方暂时无法接受，请稍后重试",
						Toast.LENGTH_SHORT).show();
			default:

				break;
			}
		};
	};

	// /////////////////////////////HandlerEnd////////////////////////////////////
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		formatBuilder = new SimpleDateFormat("MM-dd_hh:mm:ss");
		fileFormat = new SimpleDateFormat("MMddhhmmss");
		setContentView(R.layout.activity_doctor_log);
		db = DbUtils.create(this);
		MyConst.activity = this;
		initView();

	}

	private void initView() {

		getData();
		bt_pics = (Button) findViewById(R.id.bt_pics);
		bt_camera = (Button) findViewById(R.id.bt_camera);
		photo_bt = (ImageView) findViewById(R.id.photo_bt);
		photo_ll = (LinearLayout) findViewById(R.id.photo_ll);

		voice_play_ll = (LinearLayout) findViewById(R.id.voice_play_ll);
		bt_pics.setOnClickListener(this);
		bt_camera.setOnClickListener(this);
		photo_bt.setOnClickListener(this);
		et_chat_log_msg = (EditText) findViewById(R.id.et_chat_log_msg);
		et_chat_log_msg.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0, boolean arg1) {
				if (arg1) {
					voice_ll.setVisibility(View.GONE);
					photo_ll.setVisibility(View.GONE);
				}

			}
		});
		tv_chat_log_send = (TextView) findViewById(R.id.tv_chat_log_send);
		voice_bt = (ImageView) findViewById(R.id.voice_bt);
		voice_bt.setOnClickListener(this);
		lv_doctor_Chat = (XListView) findViewById(R.id.lv_doctor_chat);
		lv_doctor_Chat.setPullLoadEnable(false); // 是否开启上拉加载
		lv_doctor_Chat.setXListViewListener(this);// 上啦加载和下拉刷新的监听
		lv_doctor_Chat.reversalList();
		lv_doctor_Chat
				.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		adapter = new DoctorCharAdpater(data, this, inUser.getHeadimg(),
				MyConst.HEADIMG);
		lv_doctor_Chat.setAdapter(adapter);

		try {
			initChat();
		} catch (Exception e) {

		}

		voice_time_tx = (TextView) findViewById(R.id.voice_time_tx);
		voice_ll = (LinearLayout) findViewById(R.id.voice_ll);
		recordBt = (Button) findViewById(R.id.bt_recorder);
		playBt = (ImageView) findViewById(R.id.bt_play);
		bar = (ProgressBar) findViewById(R.id.progressBar1);
		findViewById(R.id.bt_repeat).setOnClickListener(this);

		// 录音按钮监听
		recordBt.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:// 按下
					VoiceStart();
					break;
				case MotionEvent.ACTION_MOVE:
					if (event.getY() < -100) {
						VoiceStop();
					}
					break;
				case MotionEvent.ACTION_UP:// 离开
					VoiceStop();
					break;
				}
				return false;
			}
		});

		initTitleBar();
		getDBData();

	}

	private void initTitleBar() {
		TextView tv_title_title = (TextView) findViewById(R.id.tv_title_title);
		tv_title_title.setText(inUser.getRealname());

		TextView tv_title_back = (TextView) findViewById(R.id.tv_title_back);
		tv_title_back.setVisibility(View.VISIBLE);

		tv_title_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				DoctorChatActivity.this.finish();

			}
		});

	}

	private void initChat() throws XMPPException {

		ChatManager cm = XmppTool.getConnection().getChatManager();
		final Chat newchat = cm.createChat(friendJid, null);
		tv_chat_log_send.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				// 获取text文本
				String msg = et_chat_log_msg.getText().toString();

				if (msg.length() > 0) {

					ChatModle chatModle = new ChatModle(friendName, "", MyConst
							.getACCOUNT(), "", msg, "", MyConst.CHAT_OUT,
							new Date(), 100);

					data.add(chatModle);

					// 刷新适配器
					adapter.notifyDataSetChanged();

					try {
						newchat.sendMessage(msg);
						db.save(chatModle);
						Toast.makeText(DoctorChatActivity.this, "发送成功",
								Toast.LENGTH_SHORT).show();
					} catch (XMPPException e) {
						e.printStackTrace();
					} catch (DbException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}catch(Exception e)
					{
						e.printStackTrace();
					}
					
				} else {
					Toast.makeText(DoctorChatActivity.this, "请输入信息",
							Toast.LENGTH_SHORT).show();
				}
				// 清空text
				et_chat_log_msg.setText("");
			}
		});

	}

	private void getData() {
		data = new ArrayList<ChatModle>();
		Intent intent = getIntent();
		friendJid = intent.getStringExtra("from");
		friendPath = friendJid + "/Smack";

		if (friendJid.contains("@")) {
			friendName = friendJid.substring(0, friendJid.indexOf("@"));
		}

		try {
			HistoryChat historyChat = db.findFirst(Selector
					.from(HistoryChat.class)
					.where("patientUser", "=", MyConst.getACCOUNT())
					.and(WhereBuilder.b("doctorUser", "=", friendName)));
			if (historyChat != null) {
				historyChat.setUnreadNum(0);
				db.update(historyChat);
			}
			DoctorBaseinfo doctor = db.findFirst(Selector
					.from(DoctorBaseinfo.class)
					.where("aliasAccount", "=", friendName)
					.and(WhereBuilder.b("mId", "=", MyConst.getACCOUNT())));
			if (doctor != null) {
				inUser = doctor;
			} else {
				// 网络获取
			}

		} catch (DbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		MyConst.IN_USER = "";

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MyConst.IN_USER = inUser.getAliasAccount();

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MyConst.IN_USER = "";
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.voice_bt:
			// View dialogView = initDataInputDialog(R.layout.dialog_input_chat,
			// new DataDialogListener());
			// if (null != dialogView)
			// alertDialog = DialogUtil.showDialog(this, dialogView, true);

			ClickVoiceBt();

			break;
		case R.id.bt_pics:
			ClickPicsBt();
			break;
		case R.id.bt_camera:
			clickCameraBt();
			break;
		case R.id.photo_bt:
			ClickPhtotoBt();
			break;
		case R.id.bt_repeat:
			ClickRepeatBt();

			break;
		default:
			break;
		}

	}

	public void clickCameraBt() {
		try {
			Intent openCameraIntent = new Intent(
					MediaStore.ACTION_IMAGE_CAPTURE);

			String sdcardState = Environment.getExternalStorageState();
			String sdcardPathDir = Environment.getExternalStorageDirectory()
					.getPath() + "/HealthManager/patient/temp/";
			File file = null;
			if (Environment.MEDIA_MOUNTED.equals(sdcardState)) {
				// 有sd卡，是否有temp文件夹
				File fileDir = new File(sdcardPathDir);
				if (!fileDir.exists()) {
					fileDir.mkdirs();
				}
				// 是否有headImg文件
				file = new File(sdcardPathDir + System.currentTimeMillis()
						+ ".JPEG");
			}
			if (file != null) {
				photoUri = Uri.fromFile(file);
				openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
				startActivityForResult(openCameraIntent, TAKE_PICTURE);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private int fileType = MyConst.FILE_AAC;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		fileType = MyConst.FILE_PNG;
		switch (requestCode) {

		case TAKE_PICTURE:
			if (drr.size() < 6 && resultCode == -1) {// 拍照

				final File phonoFile = new File(getPath(photoUri));

				if (phonoFile.length() > MyConst.maxuploadbytes) {
					Toast.makeText(this, "图片不能超过5M", 0).show();
				} else {
					photoFile = Environment.getExternalStorageDirectory()
							+ "/HealthManager/patient/temp/"
							+ MyConst.getACCOUNT() + "-"
							+ fileFormat.format(new Date()) + ".png";

					if (copy(getPath(photoUri), photoFile)) {

						new Thread(new Runnable() {

							@Override
							public void run() {
								try {
									sendFile(phonoFile);
								} catch (XMPPException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}).start();

					} else {
						Toast.makeText(this, "文件损坏", 0).show();
					}
				}

			}
			break;
		case RESULT_LOAD_IMAGE:
			if (drr.size() < 6 && resultCode == RESULT_OK && null != data) {// 相册返回
				Uri uri = data.getData();
				if (uri != null) {

					final File phonoFile = new File(getPath(uri));
					if (phonoFile.length() > MyConst.maxuploadbytes) {
						Toast.makeText(this, "图片不能超过5M", 0).show();
					} else {
						photoFile = Environment.getExternalStorageDirectory()
								+ "/HealthManager/patient/temp/"
								+ MyConst.getACCOUNT() + "-"
								+ fileFormat.format(new Date()) + ".png";

						if (copy(getPath(uri), photoFile)) {

							new Thread(new Runnable() {

								@Override
								public void run() {
									try {
										sendFile(phonoFile);
									} catch (XMPPException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							}).start();

						} else {
							Toast.makeText(this, "文件损坏", 0).show();
						}
					}
				}

			}
			break;
		}
	}

	private boolean copy(String fileFrom, String fileTo) {
		try {
			FileInputStream in = new java.io.FileInputStream(fileFrom);
			FileOutputStream out = new FileOutputStream(fileTo);
			byte[] bt = new byte[1024];
			int count;
			while ((count = in.read(bt)) > 0) {
				out.write(bt, 0, count);
			}
			in.close();
			out.close();
			return true;
		} catch (IOException ex) {
			return false;
		}
	}

	public void ClickPicsBt() {
		Intent i = new Intent(
				// 相册
				Intent.ACTION_PICK,
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(i, RESULT_LOAD_IMAGE);
	}

	public void ClickRepeatBt() {
		voice_play_ll.setVisibility(View.GONE);
		voice_ll.setVisibility(View.VISIBLE);
	}

	public void ClickPhtotoBt() {
		voice_ll.setVisibility(View.GONE);
		voice_play_ll.setVisibility(View.GONE);

		if (photo_ll.getVisibility() == View.VISIBLE) {
			photo_ll.setVisibility(View.GONE);

		} else {
			photo_ll.setVisibility(View.VISIBLE);
		}

	}

	public String getPath(Uri uri) {
		String source = uri.toString();
		if (source.contains("file://")) {
			return source.substring(7);
		}

		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	/**
	 * 进度条线程
	 */
	private void barUpdate() {
		barThread = new Thread(BarUpdateThread);
		barThread.start();
	}

	private void VoiceStart() {
		// 如果当前不是正在录音状态，开始录音
		if (RECODE_STATE != RECORD_ING) {
			// 自动生成的文件名
			voicePath = Environment.getExternalStorageDirectory()
					+ "/HealthManager/patient/temp/" + MyConst.getACCOUNT()
					+ "-" + fileFormat.format(new Date()) + ".aac";
			// 录音存放地址
			recorder = new MyRecorder(voicePath);

			RECODE_STATE = RECORD_ING;
			// 显示录音情况
			showVoiceDialog();
			// 开始录音
			recorder.start();

			// timeText.setVisibility(View.VISIBLE);
			bar.setVisibility(View.GONE);
			// 计时线程
			myThread();
		}
	}

	/**
	 * 录音计时线程
	 */
	private void myThread() {
		timeThread = new Thread(ImageThread);
		timeThread.start();
	}

	/**
	 * 录音线程
	 */
	private Runnable ImageThread = new Runnable() {

		@Override
		public void run() {
			recodeTime = 0.0f;
			// 如果是正在录音状态
			while (RECODE_STATE == RECORD_ING) {
				if (recodeTime >= MAX_TIME && MAX_TIME != 0) {
					recodeHandler.sendEmptyMessage(0x10);
				} else {
					try {
						Thread.sleep(200);
						recodeTime += 0.2;
						if (RECODE_STATE == RECORD_ING) {
							voiceValue = recorder.getAmplitude();
							recodeHandler.sendEmptyMessage(0x11);
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			}

		}

		Handler recodeHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case 0x10:
					// 录音超过15秒自动停止,录音状态设为语音完成

					// 如果录音时长小于1秒，显示录音失败的图标
					if (recodeTime < 1.0) {
						VoiceStop();
					} else if (recodeTime > MAX_TIME) {
						VoiceStop();
					}
					break;

				case 0x11:
					dialog_tv.setText((int) recodeTime + "S");
					setDialogImage();
					break;
				}
			}
		};
	};

	private void VoiceStop() {
		// 如果是正在录音
		if (RECODE_STATE == RECORD_ING) {
			RECODE_STATE = RECODE_ED;
			// 如果录音图标正在显示,关闭
			if (dialog.isShowing()) {
				dialog.dismiss();
			}

			// 停止录音
			recorder.stop();
			// stopRecord(extAudioRecorder);
			voiceValue = 0.0;

			if (recodeTime < MIX_TIME) {
				showWarnToast("时间太短   录音失败");

			} else {
				if (recodeTime > MAX_TIME) {
					showWarnToast("时间最多为2分钟");
				}
				voice_play_ll.setVisibility(View.GONE);
				voice_ll.setVisibility(View.GONE);
				voiceTime = (int) recodeTime;
				voice_time_tx.setText(String.valueOf(voiceTime) + "″");
				fileType = MyConst.FILE_AAC;
				File oldFile = new File(voicePath);
				if (oldFile.exists()) {

					String fileOldName = oldFile.getName();
					String fileNewName = fileOldName.substring(0,
							fileOldName.lastIndexOf("."))
							+ "-" + voiceTime + "-" + ".acc";

					final File newFile = new File(oldFile.getParentFile(),
							fileNewName);
					voicePath = newFile.getAbsolutePath();
					oldFile.renameTo(newFile);

					if (newFile.exists()) {
						new Thread(new Runnable() {

							@Override
							public void run() {
								try {

									sendFile(newFile);
								} catch (XMPPException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}).start();
					} else {
						Toast.makeText(DoctorChatActivity.this, "文件丢失，请重新录制",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(DoctorChatActivity.this, "文件丢失，请重新录制",
							Toast.LENGTH_SHORT).show();
				}

			}
		}
	}

	private Handler sendHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {

		}

	};

	private void sendFile(File file) throws XMPPException {
		long startTime = System.currentTimeMillis();
		FileTransferManager transfer = new FileTransferManager(
				XmppTool.getConnection());

		OutgoingFileTransfer out = transfer
				.createOutgoingFileTransfer(friendPath);
		try {

			out.sendFile(file, file.getName());
			fileHandler.sendEmptyMessage(3);
		} catch (XMPPException e) {
			e.printStackTrace();
		}
		int num = 0;
		while (!out.isDone()) {

			if (out.getStatus().equals(Status.error)) {
				Log.e("xmppfile", "ERROR!!! " + out.getError());
			} else {// filesize258407

				Log.e("xmppfile", out.getStatus() + "进度 " + out.getProgress());
				android.os.Message msg = new android.os.Message();
				msg.what = 4;
				msg.arg1 = (int) ((out.getAmountWritten() * 100) / out
						.getFileSize());
				fileHandler.sendMessage(msg);
				num++;
				if (num >= 10) {
					fileHandler.sendEmptyMessage(6);
					break;
				}
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		long endTime = System.currentTimeMillis();
		Log.e("xmppfile", (startTime - endTime) + "");
		Log.e("xmppfile", "//////////");
		Log.e("xmppfile", out.getStatus() + "");
		Log.e("xmppfile", out.getProgress() + "");
		Log.e("xmppfile", out.isDone() + "");
		Log.e("xmppfile", "//////////");

		Log.e("xmppfile", "发送文件结束");
		fileHandler.sendEmptyMessage(5);
	}

	// 录音Dialog图片随声音大小切换
	void setDialogImage() {
		if (voiceValue < 200.0) {
			dialog_image.setVisibility(View.INVISIBLE);
		} else {
			dialog_image.setVisibility(View.VISIBLE);
		}
		if (voiceValue > 200.0 && voiceValue < 1600) {
			dialog_image.setImageResource(R.drawable.voipic1_v_1);
		} else if (voiceValue > 1600.0 && voiceValue < 3200) {
			dialog_image.setImageResource(R.drawable.voipic2_v_1);
		} else if (voiceValue > 3200.0 && voiceValue < 7000) {
			dialog_image.setImageResource(R.drawable.voipic3_v_1);
		} else if (voiceValue > 7000.0 && voiceValue < 10000.0) {
			dialog_image.setImageResource(R.drawable.voipic4_v_1);
		} else if (voiceValue > 10000.0 && voiceValue < 14000.0) {
			dialog_image.setImageResource(R.drawable.voipic5_v_1);
		} else if (voiceValue > 14000.0 && voiceValue < 20000.0) {
			dialog_image.setImageResource(R.drawable.voipic6_v_1);
		} else if (voiceValue > 20000.0 && voiceValue < 28000.0) {
			dialog_image.setImageResource(R.drawable.voipic7_v_1);
		}
	}

	/**
	 * 显示正在录音的图标
	 */
	private void showVoiceDialog() {
		dialog = new Dialog(this, R.style.DialogStyle);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		dialog.setContentView(R.layout.item_talk_layout);
		dialog_image = (ImageButton) dialog.findViewById(R.id.talk_log);
		dialog_tv = (TextView) dialog.findViewById(R.id.talk_tv);
		dialog.show();
	}

	public void ClickVoiceBt() {
		CommonUtil.hiddenInput(this);

		photo_ll.setVisibility(View.GONE);

		if (voice_ll.getVisibility() == View.VISIBLE) {
			voice_ll.setVisibility(View.GONE);
		} else {
			voice_ll.setVisibility(View.VISIBLE);
		}
		MyRecorder tRecorder = new MyRecorder(
				Environment.getExternalStorageDirectory()
						+ "/HealthManager/temp/temp.aac");

	}

	/**
	 * 录音时间太短时Toast显示
	 */
	void showWarnToast(String text) {
		Toast toast = new Toast(this);
		LinearLayout linearLayout = new LinearLayout(this);
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		linearLayout.setPadding(20, 20, 20, 20);

		// 定义一个ImageView
		ImageView imageView = new ImageView(this);
		imageView.setImageResource(R.drawable.icon_chat_talk_no); // 图标

		TextView mTv = new TextView(this);
		mTv.setText(text);
		mTv.setTextSize(14);
		mTv.setTextColor(Color.WHITE);// 字体颜色
		// mTv.setPadding(0, 10, 0, 0);

		// 将ImageView和ToastView合并到Layout中
		linearLayout.addView(imageView);
		linearLayout.addView(mTv);
		linearLayout.setGravity(Gravity.CENTER);// 内容居中
		linearLayout.setBackgroundResource(R.drawable.trans_round_bg);// 设置自定义toast的背景

		toast.setView(linearLayout);
		toast.setGravity(Gravity.CENTER, 0, 0);// 起点位置为中间 100为向下移100dp
		toast.show();
	}

	private Runnable BarUpdateThread = new Runnable() {

		@Override
		public void run() {

			for (bar.getProgress(); bar.getProgress() <= bar.getMax();) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				handler.sendEmptyMessage(0x12);
			}
		}

		Handler handler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				if (msg.what == 0x12) {

					bar.setProgress(((int) media.getCurrentPosition()));

				}
			}
		};
	};

	public void hideSoftkeyboard() {
		try {
			IBinder iBinder = iv_catt_soundBtn.getWindowToken();
			((InputMethodManager) this
					.getSystemService(Context.INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(iBinder,
							InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (NullPointerException e) {

		}
	}

	private MyRecorder recorder;
	private LinearLayout voice_ll;
	private TextView voice_time_tx;
	private String friendJid;
	private FileTransferManager fileTransferManager;
	private String voicePath;
	private SimpleDateFormat fileFormat;
	private ImageView photo_bt;
	private Button bt_pics;
	private Button bt_camera;
	private String photoFile;

	/**
	 * 文件重命名
	 * 
	 * @param path
	 *            文件目录
	 * @param oldname
	 *            原来的文件名
	 * @param newname
	 *            新文件名
	 */
	public void renameFile(String oldPath, String newPath) {
		File oldfile = new File(oldPath);
		File newfile = new File(newPath);
		oldfile.renameTo(newfile);

	}

	private int SelectionId = 0;

	@Override
	public void onRefresh() {
		getDBData();

	}

	public void getDBData() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				android.os.Message message = new android.os.Message();
				try {
					Date date = new Date();
					if (data != null && data.size() > 0) {
						date = data.get(0).getCreateTime();
					}
					String inUser = friendName;
					if (inUser.contains("@")) {
						inUser = inUser.substring(0, inUser.indexOf("@"));
					}
					Log.e("dbutils", inUser);
					List<ChatModle> list = db.findAll(Selector
							.from(ChatModle.class)
							.where("outuser", "=", MyConst.getACCOUNT())
							.and(WhereBuilder.b("inuser", "=", inUser))
							.and(WhereBuilder.b("createTime", "<", date))
							.orderBy("createTime", true).limit(5).offset(0));

					if (list != null && list.size() > 0) {
						Collections.reverse(list);
						SelectionId = data.size();
						data.addAll(0, list);
						message.what = 1;

					} else {
						message.what = 0;

					}
					dbHandler.sendMessage(message);

				} catch (DbException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();

	}

	Handler dbHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			onLoad();
			switch (msg.what) {
			case 0:
				Toast.makeText(DoctorChatActivity.this, "没有更多的数据了",
						Toast.LENGTH_SHORT).show();
				break;
			case 1:

				adapter.notifyDataSetChanged();
				lv_doctor_Chat.setSelection(SelectionId);

				break;
			default:
				break;
			}
		}

	};
	private DoctorBaseinfo inUser;
	private String friendPath;

	@Override
	public void onLoadMore() {

	}

	private void onLoad() {

		lv_doctor_Chat.stopRefresh();
		lv_doctor_Chat.stopLoadMore();
		lv_doctor_Chat.setRefreshTime("");

	}

}
